const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = require('../config/database');
const { requireAuth, generateToken } = require('../middleware/auth');

// 登录接口
router.post('/local', async (req, res) => {
  try {
    const { identifier, password } = req.body;

    // 查询用户
    const [users] = await db.query(
      'SELECT * FROM users WHERE username = ? OR email = ?',
      [identifier, identifier]
    );

    if (users.length === 0) {
      return res.status(400).json({
        error: {
          message: '用户名或邮箱不存在'
        }
      });
    }

    const user = users[0];

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) {
      return res.status(400).json({
        error: {
          message: '密码错误'
        }
      });
    }

    // 生成 token
    const token = generateToken({
      id: user.id,
      username: user.username,
      email: user.email
    });

    // 返回用户信息和 token
    res.json({
      jwt: token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        createdAt: user.created_at,
        updatedAt: user.updated_at
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      error: {
        message: '服务器错误'
      }
    });
  }
});

// 注册接口
router.post('/local/register', async (req, res) => {
  const { username, email, password } = req.body;
  try {
    // 检查用户名或邮箱是否已存在
    const [rows] = await db.query('SELECT id FROM users WHERE username = ? OR email = ? LIMIT 1', [username, email]);
    if (rows.length) {
      return res.status(400).json({ error: { message: '用户名或邮箱已存在' } });
    }
    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);
    // 插入新用户
    const [result] = await db.query(
      'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
      [username, email, hashedPassword]
    );
    // 生成 JWT token
    const token = jwt.sign(
      { id: result.insertId, username },
      process.env.JWT_SECRET || 'yx-design-jwt-secret-key-2024',
      { expiresIn: '7d' }
    );
    res.json({
      jwt: token,
      user: {
        id: result.insertId,
        username,
        email,
        avatar: ''
      }
    });
  } catch (err) {
    console.error('注册错误', err);
    res.status(500).json({ error: { message: '服务器错误' } });
  }
});

// 更新用户信息
router.put('/me', requireAuth, async (req, res) => {
  try {
    const { username, email } = req.body;
    const userId = req.user.id;

    // 检查用户名是否已存在
    if (username) {
      const [existingUsers] = await db.query(
        'SELECT id FROM users WHERE username = ? AND id != ?',
        [username, userId]
      );
      if (existingUsers.length > 0) {
        return res.status(400).json({
          error: {
            message: '用户名已存在'
          }
        });
      }
    }

    // 检查邮箱是否已存在
    if (email) {
      const [existingEmails] = await db.query(
        'SELECT id FROM users WHERE email = ? AND id != ?',
        [email, userId]
      );
      if (existingEmails.length > 0) {
        return res.status(400).json({
          error: {
            message: '邮箱已存在'
          }
        });
      }
    }

    // 更新用户信息
    const updateFields = [];
    const updateValues = [];
    if (username) {
      updateFields.push('username = ?');
      updateValues.push(username);
    }
    if (email) {
      updateFields.push('email = ?');
      updateValues.push(email);
    }
    updateValues.push(userId);

    await db.query(
      `UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`,
      updateValues
    );

    res.json({
      message: '用户信息更新成功'
    });
  } catch (error) {
    console.error('更新用户信息错误:', error);
    res.status(500).json({
      error: {
        message: '服务器错误'
      }
    });
  }
});

// 修改密码
router.put('/me/password', requireAuth, async (req, res) => {
  try {
    const { currentPassword, newPassword } = req.body;
    const userId = req.user.id;

    // 获取当前用户信息
    const [users] = await db.query(
      'SELECT password FROM users WHERE id = ?',
      [userId]
    );

    if (users.length === 0) {
      return res.status(404).json({
        error: {
          message: '用户不存在'
        }
      });
    }

    // 验证当前密码
    const isValidPassword = await bcrypt.compare(currentPassword, users[0].password);
    if (!isValidPassword) {
      return res.status(400).json({
        error: {
          message: '当前密码错误'
        }
      });
    }

    // 加密新密码
    const hashedPassword = await bcrypt.hash(newPassword, 10);

    // 更新密码
    await db.query(
      'UPDATE users SET password = ? WHERE id = ?',
      [hashedPassword, userId]
    );

    res.json({
      message: '密码修改成功'
    });
  } catch (error) {
    console.error('修改密码错误:', error);
    res.status(500).json({
      error: {
        message: '服务器错误'
      }
    });
  }
});

// 获取当前用户信息
router.get('/me', requireAuth, async (req, res) => {
  try {
    const [users] = await db.query(
      'SELECT id, username, email, created_at, updated_at FROM users WHERE id = ?',
      [req.user.id]
    );

    if (users.length === 0) {
      return res.status(404).json({
        error: {
          message: '用户不存在'
        }
      });
    }

    const user = users[0];
    res.json({
      id: user.id,
      username: user.username,
      email: user.email,
      createdAt: user.created_at,
      updatedAt: user.updated_at
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      error: {
        message: '服务器错误'
      }
    });
  }
});

module.exports = router; 